package cn.fl.warrant.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.fl.warrant.service.IArcMgrDetailService;
import cn.fl.warrant.service.IArcRouteDetailService;
import cn.fl.warrant.service.IArcRouteMainService;
import cn.fl.warrant.vo.ArcMgrDetailVO;
import cn.fl.warrant.vo.ArcMgrMainVO;
import cn.fl.warrant.vo.ArcRouteDetailVO;
import cn.fl.warrant.vo.ArcRouteMainVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import fl.warrant.facade.archive.condition.ArcMgrDetailQC;
import fl.warrant.facade.archive.condition.ArcMgrMainQC;
import fl.warrant.facade.archive.condition.ArcRouteDetailQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;

/**
 * @Description: 巡检明细表 控制层
 */
@Controller
@RequestMapping("/archive/arcRouteDetail")
public class ArcRouteDetailController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcRouteDetailController.class);

	/**
	 * ArcRouteDetail 服务层BEAN
	 */
	@Autowired
	private IArcRouteDetailService arcRouteDetailService;
	
	@Autowired
	private IArcRouteMainService arcRouteMainService;//巡检主表
	
	@Autowired
	private IArcMgrDetailService arcMgrDetailService;//档案管理明细表

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/arcRouteDetail/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("archive/arcRouteDetail/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String mainId = request.getParameter("mainId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		ArcRouteDetailQueryCondition qc = new ArcRouteDetailQueryCondition();
		if (StringUtils.isNotEmpty(mainId)) {
			qc.setArcRouteMainId(Long.parseLong(mainId));
		}
		qc.setIsValid(1);
		qc.setIsDel(0);
		page.setCondition(qc);
		
		Pager pager = this.arcRouteDetailService.searchListPage(page);
		List<ArcRouteDetailVO> list = (List<ArcRouteDetailVO>) pager.getResultList();
		ListPageVO<ArcRouteDetailVO> listPage = new ListPageVO<ArcRouteDetailVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcRouteDetailService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			ArcRouteDetailVO vo = this.arcRouteDetailService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(@RequestBody Object formdata, HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		ArcRouteDetailVO entity = null;
		try {
			net.sf.json.JSONObject object = new net.sf.json.JSONObject();
			if(formdata != null){
				object = net.sf.json.JSONObject.fromObject(formdata);
				JSONArray grid1 = object.getJSONArray("griddata");
				String mainId = object.getString("mainId");
				//判断巡检主表ID是否为空
				if(StringUtils.isNotEmpty(mainId)){
					//作废之前的明细数据
					boolean flag = this.arcRouteDetailService.cancelDetailInfo(Long.parseLong(mainId));
					if(!flag){
						BaseLogUtils.info(logger, "add", "没有数据需要作废/作废失败.[mainId="+mainId+"]", CurrentThreadContext.getCurrentUserName());
					}
					//获取巡检明细对应的支付表号列表
					if(null != grid1){
						List<String> payNoList = new ArrayList<String>();
						for(int i=0;i<grid1.size();i++){
							net.sf.json.JSONObject gobj = grid1.getJSONObject(i);
							if(gobj.has("paySchNo")){
								payNoList.add(gobj.getString("paySchNo"));
							}else{
								continue;
							}
						}
						ArcMgrMainQC qc = new ArcMgrMainQC();
						if(CollectionUtils.isNotEmpty(payNoList)) {
							qc.setPayNOList(payNoList);
						}
						//根据支付表号获取巡检明细
						List<ArcMgrMainVO> list = this.arcRouteDetailService.getRandomRouteList(qc);
						if(CollectionUtils.isNotEmpty(list)){
							//批量插入巡检明细数据
							List<ArcRouteDetailVO> detailList = new ArrayList<ArcRouteDetailVO>();
							for(ArcMgrMainVO vo : list){
								entity = new ArcRouteDetailVO();
								entity.setArcRouteMainId(Long.parseLong(mainId));
								entity.setPaylistCode(vo.getPaySchNo());
								entity.setRouteState("0");
								entity.setRoutePerson(CurrentThreadContext.getCurrentUserName());
								entity.setIsDel(0);
								entity.setIsValid(1);
								entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
								entity.setCrtTm(new Date());
								detailList.add(entity);
							}
							boolean success = this.arcRouteDetailService.batchAddDetailInfo(detailList);
							if(!success){
								result.setSuccess(BaseConstant.IS_YESNO_NO);
								result.setInfo("新增巡检明细数据失败!");
								BaseLogUtils.info(logger, "add", "新增巡检明细数据失败1.DATA:" + JSONObject.toJSONString(detailList), CurrentThreadContext.getCurrentUserName());
							}else{
								BaseLogUtils.info(logger, "add", "新增巡检明细数据成功.DATA:" + JSONObject.toJSONString(detailList), CurrentThreadContext.getCurrentUserName());
							}
							//更新巡检主表数据
							ArcRouteMainVO mainVo = new ArcRouteMainVO();
							mainVo.setId(Long.parseLong(mainId));
							mainVo.setRouteState("1");//巡检中
							mainVo.setRouteNum(String.valueOf(detailList.size()));
							mainVo.setMdfTm(new Date());
							mainVo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
							boolean success2 = this.arcRouteMainService.modify(mainVo);
							if(!success2){
								result.setSuccess(BaseConstant.IS_YESNO_NO);
								result.setInfo("更新巡检主表数据失败!");
								BaseLogUtils.info(logger, "add", "更新巡检主表数据失败.DATA:" + JSONObject.toJSONString(mainVo), CurrentThreadContext.getCurrentUserName());
							}else{
								BaseLogUtils.info(logger, "add", "更新巡检主表数据成功.DATA:" + JSONObject.toJSONString(mainVo), CurrentThreadContext.getCurrentUserName());
							}
						}
					}else{
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("支付表号列表参数为空！获取巡检明细失败!");
						BaseLogUtils.info(logger, "add", "列表参数为空！获取巡检明细失败.[mainId="+mainId+"]", CurrentThreadContext.getCurrentUserName());
					}
				}
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "add", "新增巡检明细数据失败2.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增巡检明细数据失败3.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String  id = request.getParameter("id");
		String  routeState = request.getParameter("routeState");
		String  griddata1 = request.getParameter("griddata1");//合同资料列表
		String  griddata2 = request.getParameter("griddata2");//权证资料列表
		
		//批量更新档案管理明细数据
		List<ArcMgrDetailVO> detailList  = new ArrayList<ArcMgrDetailVO>();
		List<ArcMgrDetailVO> detailListC = JSON.parseArray(griddata1, ArcMgrDetailVO.class);//合同管理资料
		List<ArcMgrDetailVO> detailListQ = JSON.parseArray(griddata2, ArcMgrDetailVO.class);//权证资料
		//获取合同资料
		if(null != detailListC){
			for (ArcMgrDetailVO arcMgrDetailVO : detailListC) {
					arcMgrDetailVO.setMdfTm(new Date());
					arcMgrDetailVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					detailList.add(arcMgrDetailVO);
  			}
		}
		//获取权证资料
		if(null != detailListQ){
			for (ArcMgrDetailVO arcMgrDetailVO : detailListQ) {
				arcMgrDetailVO.setMdfTm(new Date());
				arcMgrDetailVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				detailList.add(arcMgrDetailVO);
			}
		}
			
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		ArcRouteDetailVO entity = null;
		try {
			entity = new ArcRouteDetailVO();
			entity.setId(Long.valueOf(id));
			entity.setRouteState(routeState);
			boolean success = this.arcRouteDetailService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		
			if(detailList!=null){
				//修改档案管理明细数据
				boolean success2 = this.arcRouteDetailService.batchUpdateMgrDetailInfo(detailList);
				if(!success2){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("修改档案管理明细失败!");
					BaseLogUtils.info(logger, "finishRoute", "修改档案管理明细失败. DATA:" + JSONObject.toJSONString(detailList), CurrentThreadContext.getCurrentUserName());
				}
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "modify", "修改失败1.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败2.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
	
	/**
	 * 刷新巡检明细列表
	 */
	@RequestMapping(value = "/refreshRouteList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object refreshRouteList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "刷新成功！");
		int num = 0;
		String routeNum = request.getParameter("routeNum");
		String buOrgCd = request.getParameter("bussDepartment");
		String cstMgrOrgCd = request.getParameter("proCompany");
		ArcMgrMainQC qc = new ArcMgrMainQC();
		if (StringUtils.isNotEmpty(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(cstMgrOrgCd)) {
			qc.setCstMgrOrgCd(cstMgrOrgCd);
		}
		//随机获取巡检明细
		List<ArcMgrMainVO> list = this.arcRouteDetailService.getRandomRouteList(qc);
		ListPageVO<ArcMgrMainVO> listPage = new ListPageVO<ArcMgrMainVO>(list, list.size());
		//设置抽取数量
		if (StringUtils.isNotEmpty(routeNum)) {
			num = Integer.parseInt(routeNum);
			//最多不能超过现有条数
			if(num > list.size()){
				num = list.size();
				result.setInfo("成功刷新"+num+"条数据！");
			}
		}
		result.setId((long)list.size());//实际条数
		//随机抽取数据
		ArcMgrMainVO mainVo = new ArcMgrMainVO();
		List<ArcMgrMainVO> randomList = new ArrayList<ArcMgrMainVO>();
		List<String> payNoList = new ArrayList<String>();
		Set<Integer> indexList = new HashSet<Integer>();//防止重复
		if (CollectionUtils.isNotEmpty(list)){
			//获取随机下标
			for (int i = 0; i < num; i++){
				int index = new Random().nextInt(list.size());
				indexList.add(index);
				while(indexList.size() < (i+1)){
					index = new Random().nextInt(list.size());
					indexList.add(index);
				}
			}
			//获取明细数据
			for(Integer n : indexList){
				mainVo = list.get(n);
				if(null != mainVo){
					randomList.add(mainVo);
					payNoList.add(mainVo.getPaySchNo());
				}
			}
			listPage = new ListPageVO<ArcMgrMainVO>(randomList, randomList.size());
			BaseLogUtils.info(logger, "refreshRouteList", "刷新巡检明细列表数据完成1. payNoList:" + JSONObject.toJSONString(payNoList), CurrentThreadContext.getCurrentUserName());
		}else{
			result.setSuccess(0);
			result.setInfo("刷新失败！可能无相应数据！");
		}
		result.setData(listPage);
		BaseLogUtils.info(logger, "refreshRouteList", "刷新巡检明细列表数据完成2. DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
		return result;
	}
	
	/**
	 * 到支付表巡检结果详情/更新页面
	 */
	@RequestMapping(value = "/toPayDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toPayDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String btnFlag = request.getParameter("btnFlag");
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("archive/arcRouteMain/arcRoutePayDetail");
		//查询对应的巡检信息
		if(StringUtils.isNotEmpty(id)){
			//1.查询巡检明细信息
			ArcRouteDetailVO detailInfo = this.arcRouteDetailService.selectById(Long.parseLong(id));
			view.addObject("detailInfo", detailInfo);
			if(detailInfo != null){
				//2.返回合同号和支付表号
				view.addObject("contractNo", detailInfo.getContractNo());
				view.addObject("payListCode", detailInfo.getPaylistCode());
			}
		}
		view.addObject("id", id);
		view.addObject("btnFlag", btnFlag);
		BaseLogUtils.info(logger, "toPayDetailPage", "跳转到支付表巡检结果详情页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 初始化权证资料列表
	 */
	@RequestMapping(value = "/initGridList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initGridList(HttpServletRequest request, HttpServletResponse response) {
		String contractNo = request.getParameter("contractNo");
		String payListCode = request.getParameter("payListCode");
		String arcLevel = request.getParameter("arcLevel");
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		ArcMgrDetailQC qc = new ArcMgrDetailQC();
		qc.setContractNo(contractNo);
		if("2".equals(arcLevel)){
			qc.setPaylistCode(payListCode);
		}
		qc.setIsDel(ArchiveConstants.IS_DEL);//未删除
		qc.setArcLevel(arcLevel);//归档级别：1 合同类  2 支付表类
		List<ArcMgrDetailVO> mgrList = this.arcMgrDetailService.searchList(qc);		
		ListPageVO<ArcMgrDetailVO> listPage = new ListPageVO<ArcMgrDetailVO>(mgrList, mgrList.size());
		BaseLogUtils.info(logger, "initGridList", "查询数据完成. DATA:" + JSONObject.toJSONString(listPage), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 完成巡检-更新巡检明细等信息
	 */
	@RequestMapping(value = "/finishRoute.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object finishRoute(@RequestBody Object formdata,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		ArcRouteDetailVO entity = new ArcRouteDetailVO();
		try {
			net.sf.json.JSONObject object = new net.sf.json.JSONObject();
			if(formdata != null){
				object = net.sf.json.JSONObject.fromObject(formdata);
				JSONArray grid1 = object.getJSONArray("griddata1");
				JSONArray grid2 = object.getJSONArray("griddata2");
				String detailId = object.getString("detailId");
				//判断巡检明细表ID是否为空
				if(StringUtils.isNotEmpty(detailId)){
					//修改巡检明细信息
					entity.setId(Long.valueOf(detailId));
					entity.setRouteState("2");//巡检结束
					entity.setRouteResult("1");//默认齐全
					entity.setMdfTm(new Date());//巡检时间
					entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					entity.setRoutePerson(CurrentThreadContext.getCurrentUserName());//巡检人员
					
					//批量更新档案管理明细数据
					List<ArcMgrDetailVO> detailList = new ArrayList<ArcMgrDetailVO>();
					//获取合同资料
					if(null != grid1){
						for(int i=0; i<grid1.size(); i++){
							int dossierCount = 0;//存档份数
							int checkedArcNum = 0;//核实存档份数
							net.sf.json.JSONObject gobj = grid1.getJSONObject(i);
							if(gobj.has("id") && null != gobj.getString("id") && !"".equals(gobj.getString("id"))){
								ArcMgrDetailVO entity2 = new ArcMgrDetailVO();
								entity2.setId(Long.parseLong(gobj.getString("id")));
								entity2.setMdfTm(new Date());
								entity2.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
								if(gobj.has("dossierCountT") && StringUtils.isNotEmpty(gobj.getString("dossierCountT")) && !"null".equals(gobj.getString("dossierCountT"))){
									dossierCount = Integer.parseInt(gobj.getString("dossierCountT"));
								}
								if(gobj.has("checkedArcNum") && StringUtils.isNotEmpty(gobj.getString("checkedArcNum")) && !"null".equals(gobj.getString("checkedArcNum"))){
									checkedArcNum = Integer.parseInt(gobj.getString("checkedArcNum"));
									entity2.setCheckedArcNum(Long.parseLong(gobj.getString("checkedArcNum")));
								}
								detailList.add(entity2);
								//巡检结果对比规则为：
								//交接单下，所有应归档资料清单的“核实存档份数”>=“存档分数”时，巡检结果为“齐全”；
								//交接单下，任一应归档资料清单的“核实存档份数”< “存档分数”时，巡检结果为“缺失”；
								if(checkedArcNum < dossierCount){
									entity.setRouteResult("0");
								}
							}else{
								continue;
							}
						}
					}
					//获取权证资料
					if(null != grid2){
						for(int i=0; i<grid2.size(); i++){
							int dossierCount = 0;//存档份数
							int checkedArcNum = 0;//核实存档份数
							net.sf.json.JSONObject gobj = grid2.getJSONObject(i);
							if(gobj.has("id") && null != gobj.getString("id") && !"".equals(gobj.getString("id"))){
								ArcMgrDetailVO entity2 = new ArcMgrDetailVO();
								entity2.setId(Long.parseLong(gobj.getString("id")));
								entity2.setMdfTm(new Date());
								entity2.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
								if(gobj.has("dossierCountT") && StringUtils.isNotEmpty(gobj.getString("dossierCountT")) && !"null".equals(gobj.getString("dossierCountT"))){
									dossierCount = Integer.parseInt(gobj.getString("dossierCountT"));
								}
								if(gobj.has("checkedArcNum") && StringUtils.isNotEmpty(gobj.getString("checkedArcNum")) && !"null".equals(gobj.getString("checkedArcNum"))){
									checkedArcNum = Integer.parseInt(gobj.getString("checkedArcNum"));
									entity2.setCheckedArcNum(Long.parseLong(gobj.getString("checkedArcNum")));
								}
								detailList.add(entity2);
								//巡检结果对比规则为：
								//交接单下，所有应归档资料清单的“核实存档份数”>=“存档分数”时，巡检结果为“齐全”；
								//交接单下，任一应归档资料清单的“核实存档份数”< “存档分数”时，巡检结果为“缺失”；
								if(checkedArcNum < dossierCount){
									entity.setRouteResult("0");
								}
							}else{
								continue;
							}
						}
					}
					//1.修改巡检明细数据
					boolean success1 = this.arcRouteDetailService.modify(entity);
					if(!success1){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("修改巡检明细失败!");
						BaseLogUtils.info(logger, "finishRoute", "修改巡检明细失败.[detailId="+detailId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
					}
					//2.修改档案管理明细数据
					boolean success2 = this.arcRouteDetailService.batchUpdateMgrDetailInfo(detailList);
					if(!success2){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("修改档案管理明细失败!");
						BaseLogUtils.info(logger, "finishRoute", "修改档案管理明细失败.[detailId="+detailId+"] DATA:" + JSONObject.toJSONString(detailList), CurrentThreadContext.getCurrentUserName());
					}
				}else{
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
					BaseLogUtils.info(logger, "finishRoute", "修改数据,主键不存在.[detailId="+detailId+"]", CurrentThreadContext.getCurrentUserName());
					return result;
				}
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "finishRoute", "修改失败1.DATA:" + JSONObject.toJSONString(formdata), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "finishRoute", "修改失败2.DATA:" + JSONObject.toJSONString(formdata), CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
	/**
	 * 巡检详情导出excel
	 */
	@RequestMapping("/exportRouteToExcel.do")
	@ResponseBody
	public Object exportRouteToExcel(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		String mainId = request.getParameter("mainId");
		ArcRouteDetailQueryCondition qc = new ArcRouteDetailQueryCondition();
		if (StringUtils.isNotEmpty(mainId)) {
			qc.setArcRouteMainId(Long.parseLong(mainId));
		}
		qc.setIsValid(ArchiveConstants.IS_VALID);
		qc.setIsDel(ArchiveConstants.IS_DEL);
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_BK_EXPORT_SUCC);
		String eFlag = request.getParameter("eFlag");//导出标识
		if(StringUtils.isEmpty(eFlag)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_PARAM_IS_BAD);
			BaseLogUtils.info(logger, "exportRouteToExcel", "导出数据,参数不完整.[eFlag="+eFlag+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			BaseLogUtils.info(logger, "exportRouteToExcel", "eFlag:"+eFlag, CurrentThreadContext.getCurrentUserName());
			String path = this.arcRouteDetailService.exportRouteDetail(qc,eFlag);
			if(StringUtils.isNotEmpty(path)){
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_BK_EXPORT_SUCC);
				result.setData(path);
				BaseLogUtils.info(logger, "exportRouteToExcel", "导出巡检详情模块数据成功", CurrentThreadContext.getCurrentUserName());
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "exportRouteToExcel", "导出巡检详情模块数据失败.", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "exportRouteToExcel", "导出巡检详情模块数据失败,系统错误..", CurrentThreadContext.getCurrentUserName(), ex);
		}
		
		return result;
	}
}

